let currentPage = 1;

function reload() {
    const pageSize = document.getElementById("pageSize").value;
    loadPage(currentPage, pageSize);
}

function jump() {
    const page = document.getElementById("jumpTo").value;
    const pageSize = document.getElementById("pageSize").value;
    loadPage(page, pageSize);
}

function loadPage(page = 1, pageSize = 10) {
    fetch(`/api/products?page=${page}&pageSize=${pageSize}`)
        .then(res => res.json())
        .then(data => {
            currentPage = data.current;
            renderData(data.data);
            renderPagination(data);
            document.getElementById("range-info").innerText = data.rangeString;
        });
}

function renderData(items) {
    const container = document.getElementById("data-container");
    container.innerHTML = "";
    items.forEach(p => {
        const div = document.createElement("div");
        div.className = "item";
        div.textContent = `${p.id}. ${p.name} - ￥${p.price}`;
        container.appendChild(div);
    });
}

function renderPagination(data) {
    const container = document.getElementById("pagination-container");
    container.innerHTML = "";

    const { hasPrev, hasNext, prev, next, pages, current } = data;

    const makeBtn = (text, page, disabled = false, active = false) => {
        const btn = document.createElement("button");
        btn.className = "page-btn";
        if (active) btn.classList.add("active");
        if (disabled) btn.classList.add("disabled");
        btn.textContent = text;
        if (!disabled && !isNaN(page)) btn.onclick = () => loadPage(page, document.getElementById("pageSize").value);
        return btn;
    };

    container.appendChild(makeBtn("« 首页", 1, !hasPrev));
    container.appendChild(makeBtn("‹ 上一页", prev, !hasPrev));

    pages.forEach(p => {
        if (p === "…") {
            const span = document.createElement("span");
            span.textContent = "…";
            container.appendChild(span);
        } else {
            container.appendChild(makeBtn(p, p, false, p === current));
        }
    });

    container.appendChild(makeBtn("下一页 ›", next, !hasNext));
    container.appendChild(makeBtn("末页 »", data.totalPages, !hasNext));
}

document.addEventListener("DOMContentLoaded", () => loadPage());
